<template>
  <div class="dashboard-container">
    <el-main>
      <!-- 数据概览 -->
      <el-row :gutter="20" class="data-overview" style="margin-bottom: 15px;">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="card-content">
              <i class="el-icon-user-solid card-icon student-icon"></i>
              <div class="card-info">
                <div class="card-title">学生总数</div>
                <div class="card-value">1,234</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card shadow="hover">
            <div class="card-content">
              <i class="el-icon-s-management card-icon teacher-icon"></i>
              <div class="card-info">
                <div class="card-title">教师总数</div>
                <div class="card-value">123</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 统计图表 -->
      <el-row :gutter="20" class="chart-row">
        <!-- 学生获奖情况（堆叠柱状图） -->
        <el-col :span="8">
          <el-card header="学生获奖情况">
            <div id="studentAwardChart" style="height: 385px;padding-left: 50px; padding-top: 1px;"></div>
          </el-card>
        </el-col>
         <el-dialog 
    title="学生获奖详情" 
    :visible.sync="awardDialogVisible"
    width="70%"
    @closed="currentAwardStudents = []">
    <el-table 
      :data="currentAwardStudents"
      stripe
      border
      style="width: 100%">
      <el-table-column 
        prop="name" 
        label="姓名"
        width="120"
        align="center"></el-table-column>
      <el-table-column 
        prop="studentId" 
        label="学号"
        width="150"
        align="center"></el-table-column>
      <el-table-column 
        prop="grade" 
        label="年级"
        width="100"
        align="center">
        <template #default="scope">
          {{ scope.row.grade }}级
        </template>
      </el-table-column>
      <el-table-column 
        prop="className" 
        label="班级"
        width="100"
        align="center">
        <template #default="scope">
          {{ scope.row.className }}班
        </template>
      </el-table-column>
      <el-table-column 
        prop="awardName" 
        label="奖项名称"
        align="center">
        <template #default="scope">
          <el-tag
            :type="awardTagType(scope.row.awardLevel)"
            effect="plain">
            {{ scope.row.awardName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        prop="date" 
        label="获奖时间"
        width="120"
        align="center"></el-table-column>
    </el-table>
  </el-dialog>
        
        <el-col :span="8" >
          <el-card header="学生详情人数">
            <!-- 年级班级选择 -->
            <div style="margin-bottom: 15px;height: 30px; padding-left: 50px;">
              <el-select 
                v-model="selectedGrade" 
                placeholder="请选择年级"
                style="margin-right: 10px;"
                @change="handleGradeChange">
                <el-option
                  v-for="grade in gradeOptions"
                  :key="grade"
                  :label="`${grade}级`"
                  :value="grade"
                />
              </el-select>
              <el-select 
                v-model="selectedClass" 
                placeholder="请选择班级"
                :disabled="!selectedGrade"
                @change="handleClassChange">
                <el-option
                  v-for="cls in classOptions"
                  :key="cls"
                  :label="`${cls}班`"
                  :value="cls"
                />
              </el-select>
            </div>

            <!-- 统计图表 -->
            <div id="classPerformanceChart" style="height: 250px; margin-top: 30px; padding-left: 50px;"></div>
            
            <!-- 底部统计 -->
            <div class="chart-footer" style="margin-top: -55px;">
              <el-tag type="danger">挂科率：{{ (failCount / totalStudents * 100).toFixed(1) }}%</el-tag>
              <el-tag type="success">评奖率：{{ (awardCount / totalStudents * 100).toFixed(1) }}%</el-tag>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="management-card">
            <template #header>
              <div class="card-header">
                <span>学生精细化管理看板</span>
                <el-tag type="info">实时更新</el-tag>
              </div>
            </template>

            <div class="filter-group">
              <el-select v-model="viewMode" size="small" @change="refreshDashboard">
                <el-option label="全院视角" value="college" />
                <el-option label="年级视角" value="grade" />
                <el-option label="班级视角" value="class" />
              </el-select>
              <el-date-picker
                v-model="timeRange"
                type="monthrange"
                size="small"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                @change="refreshDashboard"
              />
            </div>

            <div id="managementDashboard" style="height: 380px;"></div>
            
            <div class="data-summary">
              <div class="summary-item">
                <div class="label">重点关注</div>
                <div class="value danger">{{ focusStudents }}人</div>
              </div>
              <div class="summary-item">
                <div class="label">学业预警</div>
                <div class="value warning">{{ warningStudents }}人</div>
              </div>
              <div class="summary-item">
                <div class="label">进步显著</div>
                <div class="value success">{{ improvedStudents }}人</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 学生统计模块 -->
      <el-row :gutter="20" class="student-stats" >
        <el-col :span="8" style="margin-top: -150px;">
          <el-card header="学生年级分布" >
            <div id="gradeDistributionChart" style="height: 580px; padding-top: 35px;padding-left: 50px;" ></div>
            <div class="chart-footer" style="margin-bottom: 10px;margin-top: 37px;">
              <el-tag type="info">总人数：1234</el-tag>
              
            </div>
          </el-card>
        </el-col>
        
        <!-- 在template部分修改党团信息统计图 -->

<el-col :span="8" style="margin-top: -150px;">
  <el-card header="党团信息统计">
    <div style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
      <el-select 
        v-model="selectedPartyGrade" 
        placeholder="选择年级"
        size="small"
        style="width: 150px;"
        @change="refreshPartyChart">
        <el-option
          v-for="grade in gradeOptions"
          :key="grade"
          :label="`${grade}级`"
          :value="grade"
        />
      </el-select>
      <el-tag type="success" size="medium">党员总数：{{ totalPartyMembers }}</el-tag>
      <el-tag type="info" size="medium">团员总数：{{ totalLeagueMembers }}</el-tag>
    </div>
    
    <div id="partyChart" style="height: 300px;padding-left: 50px;"></div>
    
    <div class="chart-footer" style="margin-top: 15px;">
      <el-button 
        type="text" 
        size="small" 
        @click="exportData">
        导出表格
      </el-button>
    </div>
  </el-card>
</el-col>
      </el-row>
    </el-main>

    <!-- 学生党团信息详情弹窗 -->
    <el-dialog 
      title="学生党团信息详情" 
      :visible.sync="detailDialogVisible"
      width="70%"
      @closed="currentStudents = []">
      <el-table 
        :data="currentStudents"
        stripe
        border
        style="width: 100%">
        <el-table-column 
          prop="name" 
          label="姓名"
          width="120"
          align="center"></el-table-column>
        <el-table-column 
          prop="studentId" 
          label="学号"
          width="150"
          align="center"></el-table-column>
        <el-table-column 
          prop="className" 
          label="班级"
          width="100"
          align="center"></el-table-column>
        <el-table-column 
          prop="role" 
          label="角色"
          :filters="[
            { text: '党员', value: '党员' },
            { text: '预备党员', value: '预备党员' },
            { text: '团员', value: '团员' },
            { text: '三好学生', value: '三好学生' }
          ]"
          :filter-method="filterRole"
          align="center">
          <template #default="scope">
            <el-tag
              :type="roleTagType(scope.row.role)"
              effect="dark">
              {{ scope.row.role }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
   data() {
    return {
      // 弹窗相关数据
      detailDialogVisible: false,
      currentStudents: [],
      selectedPartyGrade: 2024,
      totalLeagueMembers: 0,
      totalProbationaryMembers: 0,
      // 新增获奖相关数据
      awardDialogVisible: false,
      currentAwardStudents: [],
      
      // 模拟获奖学生数据
      awardStudentData: {
        // 2021级数据
        '计算机': {
          '2021年': [
            { name: '张三', studentId: '20210101', grade: 2021, className: '1班', awardName: '国家奖学金', awardLevel: 'national', date: '2021-12-15' },
            { name: '李四', studentId: '20210102', grade: 2021, className: '2班', awardName: '校级三好学生', awardLevel: 'school', date: '2021-12-20' }
          ],
          '2022年': [
            { name: '王五', studentId: '20210201', grade: 2021, className: '3班', awardName: '全国数学竞赛一等奖', awardLevel: 'national', date: '2022-05-10' },
            { name: '赵六', studentId: '20210301', grade: 2021, className: '1班', awardName: '省级优秀学生干部', awardLevel: 'provincial', date: '2022-11-05' }
          ],
          '2023年': [
            { name: '钱七', studentId: '20210401', grade: 2021, className: '2班', awardName: '校级科技创新奖', awardLevel: 'school', date: '2023-06-15' }
          ],
          '2024年': [
            { name: '孙八', studentId: '20210501', grade: 2021, className: '3班', awardName: '优秀毕业生', awardLevel: 'school', date: '2024-04-20' }
          ]
        },
        // 2022级数据
        '电子': {
          '2022年': [
            { name: '周九', studentId: '20220101', grade: 2022, className: '1班', awardName: '国家励志奖学金', awardLevel: 'national', date: '2022-12-10' },
            { name: '吴十', studentId: '20220201', grade: 2022, className: '2班', awardName: '校级学习标兵', awardLevel: 'school', date: '2022-12-18' }
          ],
          '2023年': [
            { name: '郑十一', studentId: '20220301', grade: 2022, className: '1班', awardName: '省级英语竞赛特等奖', awardLevel: 'provincial', date: '2023-04-25' },
            { name: '王十二', studentId: '20220401', grade: 2022, className: '3班', awardName: '校级体育之星', awardLevel: 'school', date: '2023-09-12' }
          ],
          '2024年': [
            { name: '李十三', studentId: '20220501', grade: 2022, className: '2班', awardName: '全国编程大赛二等奖', awardLevel: 'national', date: '2024-03-08' }
          ],
          '2025年': [
            { name: '刘十四', studentId: '20220601', grade: 2022, className: '1班', awardName: '优秀学生干部', awardLevel: 'school', date: '2025-01-15' }
          ]
        },
        // 2023级数据
        '物理': {
          '2023年': [
            { name: '陈十五', studentId: '20230101', grade: 2023, className: '1班', awardName: '新生奖学金', awardLevel: 'school', date: '2023-10-20' },
            { name: '杨十六', studentId: '20230201', grade: 2023, className: '2班', awardName: '校级演讲比赛一等奖', awardLevel: 'school', date: '2023-11-05' }
          ],
          '2024年': [
            { name: '黄十七', studentId: '20230301', grade: 2023, className: '3班', awardName: '省级数学建模大赛三等奖', awardLevel: 'provincial', date: '2024-06-18' }
          ],
          '2025年': [
            { name: '赵十八', studentId: '20230401', grade: 2023, className: '1班', awardName: '国家奖学金', awardLevel: 'national', date: '2025-03-22' }
          ]
        },
        // 2024级数据
        '大数据': {
          '2024年': [
            { name: '钱十九', studentId: '20240101', grade: 2024, className: '1班', awardName: '优秀新生奖', awardLevel: 'school', date: '2024-09-15' }
          ],
          '2025年': [
            { name: '孙二十', studentId: '20240201', grade: 2024, className: '2班', awardName: '校级英语竞赛一等奖', awardLevel: 'school', date: '2025-04-10' },
            { name: '周廿一', studentId: '20240301', grade: 2024, className: '3班', awardName: '省级科技创新大赛优秀奖', awardLevel: 'provincial', date: '2025-05-18' }
          ]
        }
      },  // 这里缺少逗号
      
      // 模拟学生数据
      studentData: {
        '2021': {
          '1班': [
            { name: '张三', studentId: '20210101', className: '1班', role: '党员' },
            { name: '李四', studentId: '20210102', className: '1班', role: '三好学生' }
          ],
          '2班': [
            { name: '王五', studentId: '20210201', className: '2班', role: '预备党员' }
          ],
          '3班': [
            { name: '赵六', studentId: '20210301', className: '3班', role: '团员' }
          ]
        },
        '2022': {
          '1班': [
            { name: '钱七', studentId: '20220101', className: '1班', role: '团员' }
          ],
          '2班': [
            { name: '孙八', studentId: '20220201', className: '2班', role: '预备党员' }
          ],
          '3班': [
            { name: '周九', studentId: '20220301', className: '3班', role: '党员' }
          ]
        },
        '2023': {
          '1班': [
            { name: '吴十', studentId: '20230101', className: '1班', role: '团员' }
          ],
          '2班': [
            { name: '郑十一', studentId: '20230201', className: '2班', role: '三好学生' }
          ],
          '3班': [
            { name: '王十二', studentId: '20230301', className: '3班', role: '预备党员' }
          ]
        },
        '2024': {
          '1班': [
            { name: '李十三', studentId: '20240101', className: '1班', role: '团员' }
          ],
          '2班': [
            { name: '刘十四', studentId: '20240201', className: '2班', role: '三好学生' }
          ],
          '3班': [
            { name: '陈十五', studentId: '20240301', className: '3班', role: '团员' }
          ]
        }
      },  // 这里缺少逗号
      
      // 党团信息数据
      partyData: {
        '2021': { // 大四
          classes: ['1班', '2班', '3班'],
          members: {
            '团员': [15, 18, 16],
            '预备党员': [3, 5, 4],
            '党员': [2, 3, 2],
            '三好学生': [5, 6, 5]
          }
        },
        '2022': { // 大三
          classes: ['1班', '2班', '3班'],
          members: {
            '团员': [20, 22, 19],
            '预备党员': [5, 6, 5],
            '党员': [3, 4, 3],
            '三好学生': [7, 8, 6]
          }
        },
        '2023': { // 大二
          classes: ['1班', '2班', '3班'],
          members: {
            '团员': [18, 20, 17],
            '预备党员': [4, 5, 4],
            '党员': [2, 3, 2],
            '三好学生': [6, 7, 5]
          }
        },
        '2024': { // 大一
          classes: ['1班', '2班', '3班'],
          members: {
            '团员': [16, 18, 15],
            '预备党员': [3, 4, 3],
            '党员': [2, 2, 2],
            '三好学生': [5, 6, 5]
          }
        }
      },  
      
      // 年级分布数据
      gradeDistributionData: [
        {
          value: 320,
          name: '大一',
          classes: [
            { name: '1班', count: 50 },
            { name: '2班', count: 48 },
            { name: '3班', count: 55 },
            { name: '4班', count: 52 },
            { name: '5班', count: 60 },
            { name: '6班', count: 55 }
          ]
        },
        {
          value: 400,
          name: '大二',
          classes: [
            { name: '1班', count: 65 },
            { name: '2班', count: 68 },
            { name: '3班', count: 62 },
            { name: '4班', count: 70 },
            { name: '5班', count: 68 },
            { name: '6班', count: 67 }
          ]
        },
        {
          value: 350,
          name: '大三',
          classes: [
            { name: '1班', count: 58 },
            { name: '2班', count: 60 },
            { name: '3班', count: 55 },
            { name: '4班', count: 62 },
            { name: '5班', count: 60 },
            { name: '6班', count: 55 }
          ]
        },
        {
          value: 164,
          name: '大四',
          classes: [
            { name: '1班', count: 30 },
            { name: '2班', count: 28 },
            { name: '3班', count: 25 },
            { name: '4班', count: 32 },
            { name: '5班', count: 27 },
            { name: '6班', count: 22 }
          ]
        }
      ],
      selectedGrade: null,
      selectedClass: null,
      gradeOptions: [2021, 2022, 2023, 2024],
      classOptions: [],
      // 班级表现数据
      performanceData: {
        total: 0,
        fail: 0,
        award: 0,
        activity: 0,
        violation: 0,
        warning: 0
      },
      viewMode: 'college',
      timeRange: [
        new Date(2025, 0),
        new Date()
      ],
      managementData: {
        focusStudents: 23,
        warningStudents: 15,
        improvedStudents: 37,
        trend: {
          warning: [12, 15, 18, 20, 17, 14, 16],
          improvement: [8, 10, 15, 18, 22, 25, 20]
        },
        correlation: [
          [65, 80], [72, 75], [58, 65], [82, 88], 
          [75, 78], [68, 72], [80, 85], [63, 70]
        ],
        distribution: [78, 85, 92, 88]
      }
    }
  },
  computed: {
    totalStudents() {
      return this.performanceData.total || 1
    },
    failCount() {
      return this.performanceData.fail || 0
    },
    awardCount() {
      return this.performanceData.award || 0
    },
    totalPartyMembers() {
      return Object.values(this.partyData).reduce((total, grade) => {
        return total + Object.values(grade.members).flat().reduce((a, b) => a + b, 0)
      }, 0)
    }
  },
  
  methods: {
    // 班级选择处理方法
    handleGradeChange(grade) {
      this.classOptions = Array.from({length: 6}, (_, i) => i + 1)
      this.selectedClass = null
      this.initClassPerformanceChart()
    },
    handleClassChange(cls) {
      this.performanceData = {
        total: Math.floor(Math.random() * 40 + 30),
        fail: Math.floor(Math.random() * 10),
        award: Math.floor(Math.random() * 15),
        activity: Math.floor(Math.random() * 20),
        violation: Math.floor(Math.random() * 5),
        warning: Math.floor(Math.random() * 8)
      }
      this.initClassPerformanceChart()
    },

    // 图表初始化方法
    initCharts() {
      this.initAwardChart()
      this.initGradeDistributionChart()
      this.initPartyChart()  // 改为 initPartyChart
      this.initClassPerformanceChart()
    },

    // 修改后的学生获奖情况图表方法
    initAwardChart() {
      const chart = echarts.init(document.getElementById('studentAwardChart'))
      const self = this; // 保存 this 引用
      
      const option = {
        tooltip: { 
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: function(params) {
            // 在 formatter 内部使用 self 访问 Vue 实例
            let result = `<div style="margin-bottom:5px;font-weight:bold">${params[0].name}</div>`
            params.forEach(item => {
              const count = self.getAwardCount(item.name, item.seriesName)
              result += `
                <div style="display:flex;align-items:center;margin:3px 0">
                  <div style="width:10px;height:10px;background:${item.color};margin-right:5px"></div>
                  <div>${item.seriesName}: ${item.value}项 (${count}人)</div>
                </div>
              `
            })
            return result
          }
        },
        legend: {
          data: ['2021年', '2022年', '2023年', '2024年', '2025年'],
          bottom: 0
        },
        xAxis: {
          type: 'category',
          data: ['计算机', '电子', '物理', '大数据'],
          axisLabel: { 
            color: '#666',
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '奖项数量',
          axisLabel: { color: '#666' }
        },
        series: [
          {
            name: '2021年',
            type: 'bar',
            stack: '学年',
            data: [15, 0, 0, 0],
            itemStyle: { color: '#67C23A' }
          },
          {
            name: '2022年',
            type: 'bar',
            stack: '学年',
            data: [12, 18, 0, 0],
            itemStyle: { color: '#409EFF' }
          },
          {
            name: '2023年',
            type: 'bar',
            stack: '学年',
            data: [10, 15, 20, 0],
            itemStyle: { color: '#E6A23C' }
          },
          {
            name: '2024年',
            type: 'bar',
            stack: '学年',
            data: [8, 12, 18, 25],
            itemStyle: { color: '#F56C6C' }
          },
          {
            name: '2025年',
            type: 'bar',
            stack: '学年',
            data: [0, 10, 15, 20],
            itemStyle: { color: '#36CBCB' }
          }
        ]
      }
      
      chart.setOption(option)
      
      // 添加点击事件
      chart.on('click', params => {
        const grade = params.name  // 如 '2021级'
        const year = params.seriesName  // 如 '2021年'
        
        // 获取对应年级和学年的获奖学生
        this.currentAwardStudents = this.awardStudentData[grade]?.[year] || []
        
        if (this.currentAwardStudents.length > 0) {
          this.awardDialogVisible = true
        } else {
          this.$message.info('该学年没有获奖记录')
        }
      })
    },
    
    // 获取获奖人数
    getAwardCount(grade, year) {
      return this.awardStudentData[grade]?.[year]?.length || 0
    },
    
    // 奖项标签样式
    awardTagType(level) {
      const types = {
        'national': 'danger',
        'provincial': 'warning',
        'school': 'success'
      }
      return types[level] || 'info'
    },

    // 班级表现图表
    initClassPerformanceChart() {
      const chart = echarts.init(document.getElementById('classPerformanceChart'))
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          bottom: '45%'  // 增加底部间距
        },
        xAxis: {
          type: 'category',
          data: ['班级人数', '挂科人数', '评奖人数', '综测活动', '违规人数', '学业预警'],
          axisLabel: {
            rotate: 30,      // 旋转30度
            interval: 0,     // 强制显示所有标签
            fontSize: 12,    // 适当缩小字号
            margin: 15       // 增加标签间距
          }
        },
        yAxis: { 
          type: 'value', 
          axisLabel: {
            fontSize: 12    // 统一字号
          }
        },
        series: [{
          data: [
            this.performanceData.total,
            this.performanceData.fail,
            this.performanceData.award,
            this.performanceData.activity,
            this.performanceData.violation,
            this.performanceData.warning
          ],
          type: 'bar',
          itemStyle: {
            color: (params) => {
              const colors = ['#5470C6', '#EE6666', '#91CC75', '#FAC858', '#73C0DE', '#3BA272']
              return colors[params.dataIndex]
            }
          }
        }]
      }
      chart.setOption(option)
    },
    
    refreshDashboard() {
      this.initManagementDashboard()
    },
    
    // 管理看板图表初始化
    initManagementDashboard() {
      const chart = echarts.init(document.getElementById('managementDashboard'))
      const option = {
        tooltip: { trigger: 'axis' },
        grid: [
          { left: '5%', top: '10%', width: '45%', height: '30%' },
          { right: '3%', top: '10%', width: '45%', height: '30%' },
          { left: '5%', top: '55%', width: '90%', height: '35%' }
        ],
        xAxis: [
          {
            gridIndex: 0,
            type: 'category',
            data: ['9月', '10月', '11月', '12月', '1月', '2月', '3月'],
            axisLabel: { color: '#606266', fontSize: 12 }
          },
          {
            gridIndex: 1,
            type: 'value',
            name: '学业成绩',
            min: 50,
            max: 100,
            axisLabel: { color: '#606266', fontSize: 12 }
          },
          {
            gridIndex: 2,
            type: 'category',
            data: ['心理健康', '宿舍卫生', '课堂出勤', '课外活动'],
            axisLabel: { 
              color: '#606266',
              fontSize: 12,
              rotate: 30,
              interval: 0
            }
          }
        ],
        yAxis: [
          {
            gridIndex: 0,
            type: 'value',
            name: '人数',
            axisLabel: { color: '#606266', fontSize: 12 }
          },
          {
            gridIndex: 1,
            type: 'value',
            name: '日常行为分',
            min: 60,
            max: 95,
            axisLabel: { color: '#606266', fontSize: 12 }
          },
          {
            gridIndex: 2,
            type: 'value',
            name: '评分',
            axisLabel: { color: '#606266', fontSize: 12 }
          }
        ],
        series: [
          {
            type: 'line',
            xAxisIndex: 0,
            yAxisIndex: 0,
            name: '预警趋势',
            data: this.managementData.trend.warning,
            lineStyle: { color: '#F56C6C', width: 2 },
            symbol: 'circle',
            symbolSize: 8
          },
          {
            type: 'line',
            xAxisIndex: 0,
            yAxisIndex: 0,
            name: '进步趋势',
            data: this.managementData.trend.improvement,
            lineStyle: { color: '#67C23A', width: 2 },
            areaStyle: { color: 'rgba(103,194,58,0.1)' }
          },
          {
            type: 'scatter',
            xAxisIndex: 1,
            yAxisIndex: 1,
            symbolSize: 10,
            data: this.managementData.correlation,
            itemStyle: {
              color: ({ value }) => value[0] > 75 ? '#36CBCB' : '#409EFF',
              borderColor: '#fff',
              borderWidth: 1
            }
          },
          {
            type: 'bar',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: this.managementData.distribution,
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#36CBCB' },
                { offset: 1, color: '#409EFF' }
              ])
            }
          }
        ]
      }
      chart.setOption(option)
    },

    // 年级分布图表（饼图）
    initGradeDistributionChart() {
      const chart = echarts.init(document.getElementById('gradeDistributionChart'))
      chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const classInfo = params.data.classes.map(c => 
              `${c.name}: ${c.count}人`
            ).join('<br/>')
            return `
              ${params.name}（总人数: ${params.value}人）<br/>
              ${classInfo}
            `
          }
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.gradeDistributionData.map(item => item.name)
        },
        series: [{
          name: '年级分布',
          type: 'pie',
          radius: ['40%', '65%'],
          center: ['50%', '55%'],
          avoidLabelOverlap: true,
          label: {
            show: true,
            formatter: '{b}\n总人数: {c}人',
            fontSize: 14,
            lineHeight: 20
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16
            }
          },
          data: this.gradeDistributionData,
          itemStyle: {
            color: (params) => {
              const colorList = ['#36CBCB', '#409EFF', '#67C23A', '#F56C6C']
              return colorList[params.dataIndex]
            }
          }
        }]
      })
    },

    // 党团信息图表（完整实现）
    initGradeChart() {
      const chart = echarts.init(document.getElementById('gradeChart'))
      const option = {
        tooltip: {
          trigger: 'axis',
          confine: true,
          backgroundColor: '#fff',
          borderWidth: 1,
          borderColor: '#ddd',
          padding: [10, 15],
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          formatter: params => {
            const grade = params[0].name.replace('级', '')
            return `
              <div style="min-width: 400px;">
                <div style="font-size: 16px; color: #409EFF; border-bottom: 1px solid #eee; 
                         padding-bottom: 8px; margin-bottom: 12px;">
                  ${params[0].name}党团信息
                </div>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                  ${this.partyData[grade].classes.map((cls, index) => `
                    <div style="border: 1px solid #eee; border-radius: 4px; padding: 10px;">
                      <div style="font-weight: 500; margin-bottom: 8px;">${cls}</div>
                      <div style="display: flex; gap: 15px; flex-wrap: wrap;">
                        ${params.map(p => `
                          <div style="flex: 1; min-width: 80px;">
                            <div style="color: #666;">${p.seriesName}</div>
                            <div style="font-weight: bold; color: ${p.color};">${p.data[index]}人</div>
                          </div>
                        `).join('')}
                      </div>
                    </div>
                  `).join('')}
                </div>
              </div>
            `
          }
        },
        legend: {
          data: ['团员', '预备党员', '党员', '三好学生'],
          bottom: 10
        },
        xAxis: {
          type: 'category',
          data: Object.keys(this.partyData).map(g => `${g}级`),
          axisLabel: {
            color: '#666',
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          axisLabel: { color: '#666' }
        },
        series: [
          {
            name: '团员',
            type: 'bar',
            stack: 'category',
            data: Object.values(this.partyData).map(g => g.members['团员'].reduce((a, b) => a + b, 0)),
            itemStyle: { color: '#36CBCB' }
          },
          {
            name: '预备党员',
            type: 'bar',
            stack: 'category',
            data: Object.values(this.partyData).map(g => g.members['预备党员'].reduce((a, b) => a + b, 0)),
            itemStyle: { color: '#409EFF' }
          },
          {
            name: '党员',
            type: 'bar',
            stack: 'category',
            data: Object.values(this.partyData).map(g => g.members['党员'].reduce((a, b) => a + b, 0)),
            itemStyle: { color: '#F56C6C' }
          },
          {
            name: '三好学生',
            type: 'bar',
            stack: 'category',
            data: Object.values(this.partyData).map(g => g.members['三好学生'].reduce((a, b) => a + b, 0)),
            itemStyle: { color: '#67C23A' }
          }
        ]
      }
      chart.setOption(option)

      // 点击事件处理
      chart.on('click', params => {
        const grade = params.name.replace('级', '')
        const classIndex = params.dataIndex
        const className = this.partyData[grade].classes[classIndex]
        const roleType = params.seriesName
        
        this.currentStudents = this.studentData[grade]?.[className]
          ?.filter(student => student.role === roleType) || []
        
        if (this.currentStudents.length > 0) {
          this.detailDialogVisible = true
        } else {
          this.$message.info('当前筛选条件下无学生数据')
        }
      })
    },
    // 重新设计党团信息图表
   // 在methods中修改initPartyChart方法
initPartyChart() {
  const chart = echarts.init(document.getElementById('partyChart'))
  const grade = this.selectedPartyGrade
  const data = this.partyData[grade]
  
  // 计算总数用于百分比显示
  const totals = data.classes.map((cls, i) => 
    Object.values(data.members).reduce((sum, arr) => sum + arr[i], 0)
  )
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function(params) {
        // 多级tooltip设计
        let html = `<div style="font-weight:bold;margin-bottom:10px;">${params[0].name}</div>`
        let total = 0
        
        params.forEach(param => {
          total += param.value
          const percent = ((param.value / totals[param.dataIndex]) * 100).toFixed(1)
          html += `
            <div style="display:flex;align-items:center;margin:5px 0;">
              <div style="width:10px;height:10px;background:${param.color};margin-right:5px;"></div>
              <div>${param.seriesName}: ${param.value}人</div>
              <div style="margin-left:auto;color:#999;">${percent}%</div>
            </div>
          `
        })
        
        html += `<div style="margin-top:8px;border-top:1px solid #eee;padding-top:8px;">
                   <strong>总计: ${total}人</strong>
                 </div>`
        return html
      }
    },
    legend: {
      data: Object.keys(data.members),
      bottom: 0,
      itemWidth: 12,
      itemHeight: 12
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.classes,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: Object.entries(data.members).map(([role, values], index) => ({
      name: role,
      type: 'bar',
      stack: 'total',
      emphasis: { focus: 'series' },
      data: values,
      itemStyle: {
        color: this.getRoleColor(role),
        borderRadius: [2, 2, 0, 0]
      },
      label: {
        show: true,
        position: 'inside',
        formatter: ({ value }) => value > 0 ? value : '',
        fontSize: 12,
        color: '#fff'
      }
    }))
  }
  
  chart.setOption(option)
  
  // 更新成员总数
  this.totalLeagueMembers = data.members['团员'].reduce((a, b) => a + b, 0)
  this.totalPartyMembers = data.members['党员'].reduce((a, b) => a + b, 0) + 
                          data.members['预备党员'].reduce((a, b) => a + b, 0)
  
  // 点击事件处理
  chart.on('click', params => {
    const className = params.name
    const role = params.seriesName
    this.currentStudents = this.getStudentsByClassAndRole(grade, className, role)
    this.detailDialogVisible = true
  })
},

// 添加辅助方法
getStudentsByClassAndRole(grade, className, role) {
  return (this.studentData[grade]?.[className] || [])
    .filter(student => student.role === role)
},

// 根据角色获取颜色
getRoleColor(role) {
  const colorMap = {
    '党员': '#f56c6c',
    '预备党员': '#e6a23c',
    '团员': '#36cbcb',
    '三好学生': '#67c23a'
  }
  return colorMap[role] || '#409eff'
},
    
    // 根据班级获取学生
    getStudentsByClass(grade, className) {
      return this.studentData[grade]?.[className] || []
    },
     // 根据角色获取学生
    getStudentsByRole(grade, role) {
      return Object.values(this.studentData[grade] || {})
        .flat()
        .filter(student => student.role === role)
    },
    
    // 刷新图表
    refreshPartyChart() {
      this.initPartyChart()
    },
    






    // 导出数据为CSV
    exportData() {
      try {
        const csvContent = [
          ['年级', '班级', '姓名', '学号', '角色'].join(','),
          ...Object.entries(this.studentData).flatMap(([grade, classes]) =>
            Object.entries(classes).flatMap(([cls, students]) =>
              students.map(student => 
                [grade, cls, student.name, student.studentId, student.role].join(',')
              )
            )
          )
        ].join('\n')

        const blob = new Blob([`\uFEFF${csvContent}`], { type: 'text/csv;charset=utf-8' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `党团信息_${this.formatDate(new Date())}.csv`
        link.click()
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败，请检查数据')
      }
    },
    
    // 格式化日期为YYYYMMDD
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}${month}${day}`
    },
    
    // 角色标签样式
    roleTagType(role) {
      const types = {
        '党员': 'danger',
        '预备党员': 'warning',
        '三好学生': 'success',
        '团员': 'info'
      }
      return types[role] || ''
    },
    
    // 表格过滤方法
    filterRole(value, row) {
      return row.role === value
    }
  },
  mounted() {
    this.initCharts()
    this.initClassPerformanceChart()
    this.initManagementDashboard()
    this.initPartyChart()
  },
  beforeDestroy() {
    [
      'managementDashboard',
      'studentAwardChart', 
      'classPerformanceChart',
      'gradeDistributionChart',
      'gradeChart'
    ].forEach(id => {
      const dom = document.getElementById(id)
      if (dom) echarts.dispose(dom)
    })
  }
}
</script>

<style scoped>
/* 添加弹窗表格样式 */
.el-dialog__body {
  padding: 15px 20px;
}

.el-table .el-tag {
  font-size: 13px;
  padding: 0 8px;
  height: 26px;
  line-height: 26px;
}


/* 新增样式 */
.chart-footer {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 响应式调整 */
@media (max-width: 768px) {
  #partyChart {
    height: 250px !important;
  }
  
  .chart-footer {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}






#gradeDistributionChart {
  height: 320px !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  #gradeDistributionChart {
    height: 250px !important;
  }
  
  /* 调整图例位置 */
  :deep(.echarts-legend) {
    position: relative !important;
    left: auto !important;
    top: auto !important;
  }
}
.management-card {
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.filter-group {
  display: flex;
  gap: 10px;
  margin: 0 15px 15px;
}

.data-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin: 15px;
}

.summary-item {
  background: #f8fafd;
  border-radius: 6px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.04);
  
  .label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 6px;
  }
  
  .value {
    font-size: 16px;
    font-weight: 600;
    
    &.danger { color: #F56C6C; }
    &.warning { color: #E6A23C; }
    &.success { color: #67C23A; }
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .filter-group {
    flex-direction: column;
  }
  
  #managementDashboard {
    height: 320px !important;
  }
}

@media (max-width: 768px) {
  #managementDashboard {
    height: 280px !important;
  }
  
  .data-summary {
    grid-template-columns: 1fr;
  }
}

/* 调整图表容器高度 */
#classPerformanceChart {
  height: 350px !important;
  margin-top: 10px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  #classPerformanceChart {
    height: 280px !important;
  }
  
  .el-select {
    width: 48%;
  }
}

.dashboard-container {
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 新增图表响应式样式 */
@media (max-width: 768px) {
  #studentAwardChart,
  #gradeDistributionChart,
  #gradeChart {
    height: 250px !important;
  }
}

/* 弹窗表格样式优化 */
.el-table .el-tag {
  letter-spacing: 1px;
  padding: 0 8px;
}

.chart-footer {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 响应式调整 */
@media (max-width: 768px) {
  #gradeChart {
    height: 250px !important;
  }
  
  .chart-footer {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>